<!--
 * @Description: 
 * @Version: 1.0
 * @Autor: gaoluo
 * @Date: 2021-08-20 22:58:46
 * @LastEditors: gaoluo
 * @LastEditTime: 2021-12-05 18:50:31
 * @FilePath: /nhw/src/views/Work/Snapshot/index.vue
-->
<template>
  <Layout
    class="snapshot-container"
    title="随手拍"
    border
    @click-right="$router.push({ name: 'SnapshotRecord' })"
  >
    <template #right>
      <Icon name="notes-o" />
    </template>
    <template #default>
      <!-- 表单 start -->
      <!-- <h2>随手拍记录</h2> -->
      <Form
        @submit="checkOrder"
        :show-error="false"
        validate-first
        validate-trigger="onSubmit"
      >
        <Cell
          title="安全隐患种类"
          :value="index === -1 ? '请选择' : columns[index].name"
          is-link
          @click="showPicker"
          class="van-cell--required"
          style="color: #646566"
        />

        <Field
          v-model="place"
          label="拍照位置"
          placeholder="请输入拍照位置"
          required
          input-align="right"
          :rules="[
            {
              required: true,
              message: (value) => {
                $toast('请输入拍照位置');
              },
            },
          ]"
        />
        <Field
          v-model="question"
          autosize
          label="问题描述"
          type="textarea"
          placeholder="请简述您想要反馈的问题"
          required
          input-align="right"
          :rules="[
            {
              required: true,
              message: (value) => {
                $toast('请简述您想要反馈的问题');
              },
            },
          ]"
        />
        <Field
          v-model="contact"
          label="联系人"
          placeholder="请输入联系人"
          required
          input-align="right"
          :rules="[
            {
              required: true,
              message: () => {
                $toast('请输入联系人');
              },
            },
          ]"
        />
        <Field
          v-model="phone"
          label="联系电话"
          placeholder="请输入联系电话"
          required
          input-align="right"
          maxlength="11"
          :rules="[
            {
              required: true,
              message: () => {
                $toast('请输入联系电话');
              },
            },
            {
              pattern,
              message: () => {
                $toast('请输入正确电话号码');
              },
            },
          ]"
        />
        <Field
          label="请拍摄现场照片"
          required
          label-width="8em"
          readonly
          :border="false"
          :rules="[
            {
              validator,
              message: () => {
                $toast('请拍摄现场照片或视频');
              },
            },
          ]"
        />
        <Cell>
          <Uploader v-model="fileList" multiple :max-count="3" />
        </Cell>
        <Field
          label="请拍摄现场视频"
          required
          label-width="8em"
          readonly
          :border="false"
          :rules="[
            {
              validator,
              message: () => {
                $toast('请拍摄现场视频或照片');
              },
            },
          ]"
        />
        <Cell>
          <Uploader
            v-model="videoList"
            multiple
            :preview-image="false"
            :max-count="1"
            accept="video/*"
            capture="camera"
            :before-read="beforeRead"
            v-show="videoList.length <= 0"
          />
          <PrevVideo
            @deleteVideo="deleteVideo"
            :videoUrl="videoList.length > 0 ? videoList[0].content : ''"
            v-for="value in videoList.length"
            :key="value"
          />
        </Cell>
        <Cell class="loca">
          <Icon
            name="location"
            color="#6A6D73"
            size=".5rem"
            class="loca-icon"
          />
          {{ address }}
        </Cell>
        <!-- 表单 end -->
        <!-- 提交 start-->
        <div class="btn-wrap">
          <Button plain native-type="submit">提交</Button>
        </div>
        <!-- 提交 end-->
      </Form>
      <!-- 弹出选择框1 -->
      <Popup v-model="show" position="bottom" :style="{ height: '43%' }">
        <Picker
          show-toolbar
          :columns="columns"
          value-key="name"
          item-height="1rem"
          @confirm="onConfirm"
          @cancel="onCancel"
        >
        </Picker>
      </Popup>
      <!-- 弹出选择框 -->
    </template>
  </Layout>
</template>

<script>
import Layout from "components/Layout";
import PrevVideo from "components/PrevVideo";
import {
  Uploader,
  Icon,
  Button,
  Field,
  Cell,
  Form,
  Dialog,
  Popup,
  Picker,
} from "vant";
import { problemClapSave, problemClapList, getDictionary } from "@/api/work.js";
import uploadImages from "@/utils/uploadImages.js";
import getPosition from "@/utils/getPosition.js";
export default {
  name: "Snapshot",

  components: {
    Layout,
    PrevVideo,
    Uploader,
    Icon,
    Button,
    Field,
    Cell,
    Form,
    Popup,
    Picker,
  },

  data() {
    return {
      show: false,
      place: "",
      question: "",
      contact: "",
      phone: "",
      pattern: /^1[3-9][0-9]{9}$/,
      fileList: [],
      videoList: [],
      address: "无锡拈花湾景区梵天花海",
      lng: 120.068788,
      lat: 31.417695,
      userInfo: {},
      org: "",
      columns: [],
      index: -1,
    };
  },
  created() {
    this.load();
  },

  beforeRouteLeave(to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    if (to.name === "Work") {
      this.index = -1;
      this.place = "";
      this.question = "";
      this.contact = "";
      this.phone = "";
      this.fileList = [];
      this.videoList = [];
    }
    next();
  },
  mounted() {},
  methods: {
    load() {
      this.city();
      this.userInfo = JSON.parse(window.localStorage.getItem("userInfo"));
      this.contact = this.userInfo.userName;
      this.phone = this.userInfo.mobile;
      this.org = window.localStorage.getItem("orgNo");
      getDictionary("RskmgSourceControl-category").then((res) => {
        this.columns = res.param.data;
      });
    },
    showPicker() {
      this.show = true;
    },
    onConfirm(value, index) {
      this.show = false;
      this.index = index;
    },
    onCancel() {
      this.show = false;
    },

    async checkOrder() {
      if (!this.lng || !this.lat) {
        this.$toast.fail("位置获取失败,请重试");
        return;
      }
      if (!this.columns[this.index].id) {
        this.$toast.fail("请选择隐患种类");
        return;
      }
      //校验是否有重复单据
      if (
        await this.haveRepetOrder({
          point: this.lng + "," + this.lat,
          orgNo: this.org,
        })
      ) {
        Dialog.confirm({
          title: "提示",
          message: "该订单疑似为：重复订单！是否继续上报?",
          confirmButtonText: "继续上报",
          cancelButtonText: "查看重复订单",
          confirmButtonColor: "#E16712",
        })
          .then(() => {
            console.log("确认");
            this.onSubmit();
          })
          .catch(() => {
            console.log("取消");
            //查看重复订单页面
            setTimeout(() => {
              this.$router.push({
                name: "SnapshotRepeated",
                query: { point: this.lng + "," + this.lat },
              });
            }, 500);
          });
        return;
      }
      this.onSubmit();
    },

    //提交数据
    async onSubmit() {
      try {
        let pic = "";
        let video = "";

        //上传图片视频
        if (this.fileList.length > 0) {
          this.$toast.loading({
            message: "正在上传图片",
            duration: 0,
          });
          pic = await uploadImages(this.fileList);
          pic = pic.join(",");
        }
        if (this.videoList.length > 0) {
          this.$toast.loading({
            message: "正在上传视频",
            duration: 0,
          });
          video = await uploadImages(this.videoList);
          video = video.join(",");
        }

        const data = {
          orgNo: this.org, //公司主键
          lng: this.lng, //经度
          lat: this.lat, //纬度
          address: this.address, //经纬度地址
          findUser: this.contact, //联系人
          findMobile: this.phone, //联系人电话
          remark: this.question, //问题描述
          yhType: this.columns[this.index].id, //类型
          rpcArea: this.place, //地点
          pic, //图片组件
          video, //视频组件
        };

        this.$toast.loading({
          message: "提交中...",
          duration: 0,
        });
        //发送提交
        await problemClapSave(data);

        this.$toast.success("提交成功！");
        //返回列表页
        setTimeout(() => {
          this.$router.replace({ name: "SnapshotRecord" });
        }, 500);
      } catch (error) {
        console.log(error);
        this.$toast.fail("提交失败！");
      }
    },
    //查询是否有重复订单
    async haveRepetOrder(params) {
      const res = await problemClapList(params);
      return res.param.data.length > 0;
    },
    //图片添加校验
    validator() {
      return this.fileList.length > 0 || this.videoList.length > 0;
    },
    //位置获取
    city() {
      getPosition()
        .then((res) => {
          this.address = res.address;
          this.lng = res.lng;
          this.lat = res.lat;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //上传视频时间校验
    beforeRead(file) {
      return new Promise((resolve, reject) => {
        const url = URL.createObjectURL(file);
        const dom = new Audio(url);
        dom.addEventListener("loadedmetadata", (e) => {
          if (dom.duration > 15) {
            this.$toast("视频长度必须小于15秒");
            reject();
          } else {
            resolve();
          }
        });
      });
    },
    deleteVideo() {
      this.videoList = [];
    },
  },
};
</script>

<style lang="less" scoped>
@import url("~style/mixin.less");
@import url("~style/var.less");

.snapshot-container {
  // .backOrange();
  h2 {
    // color: #fff;
    line-height: 3em;
    text-indent: 0.4em;
    position: relative;
  }
  .van-form {
    // .card();
    background: #fff;
    position: relative;
  }
  .btn-wrap {
    width: 100%;
    padding-bottom: 44px;
    .flex();
    .van-button {
      .clickableBtn();
      overflow: hidden;
      margin: 30px auto 0;
    }
  }
  .loca > div {
    display: flex;
    align-items: center;
    .loca-icon {
      margin-right: 10px;
    }
  }

  /deep/.van-uploader__upload {
    border: 2px dashed @primary;
    width: 110px;
    height: 110px;
    border-radius: 4px;
    background: #fff;
    .van-icon {
      color: @primary;
      &::before {
        content: "\F0A2";
      }
    }
  }
  /deep/ .van-uploader__preview .van-uploader__preview-image {
    width: 110px;
    height: 110px;
  }
}

// /deep/ .van-field__error-message {
//   text-indent: -2em;
// }

// /deep/ .van-field__control {
//   text-align: right;
// }
.van-icon {
  vertical-align: sub;
}
</style>